package com.jdz.tools;


import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.jdz.entities.FlyRow;
import com.jdz.entities.NoiseRow;
import com.sun.rowset.internal.Row;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ControlUtil {
    //存储噪声文件数据
    public static final ArrayList<String> fileNames_noise = new ArrayList<String>();
    public static final ArrayList<NoiseRow> list_noise = new ArrayList<NoiseRow>();
    //存储飞行文件数据
    public static final ArrayList<String> fileNames_fly = new ArrayList<String>();
    public static final ArrayList<FlyRow> list_fly = new ArrayList<FlyRow>();
    //上传文件夹路径
    public static final String uploadPath = "E:/upload/";
    //标记飞行数据，还是噪声数据
    public static final int NOISE_TYPE = 1;
    public static final int FLY_TYPE = 2;


    public static String uploadFile(MultipartFile file, int fileType) {

        String pathString = null;
        if (file != null) {
            //获取上传的文件名称
            String filename = file.getOriginalFilename();
            //文件上传时，chrome与IE/Edge对于originalFilename处理方式不同
            //chrome会获取到该文件的直接文件名称，IE/Edge会获取到文件上传时完整路径/文件名
            //Check for Unix-style path
            int unixSep = filename.lastIndexOf('/');
            //Check for Windows-style path
            int winSep = filename.lastIndexOf('\\');
            //cut off at latest possible point
            int pos = (winSep > unixSep ? winSep : unixSep);
            if (pos != -1) {
                filename = filename.substring(pos + 1);
                pathString = uploadPath + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + filename;//上传到本地
            } else {
                pathString = uploadPath + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + filename;//上传到本地
            }
        }
        try {
            File files = new File(pathString);//在内存中创建File文件映射对象
            //打印查看上传路径
            System.out.println(pathString);
            if (!files.getParentFile().exists()) {//判断映射文件的父文件是否真实存在
                files.getParentFile().mkdirs();//创建所有父文件夹
            }
            file.transferTo(files);//采用file.transferTo 来保存上传的文件

            //将数据保存到List对象中去
            if (fileType == NOISE_TYPE) {
                fileNames_noise.add(file.getOriginalFilename());
                readNoiseFile(pathString);
                //System.out.println(list_noise);
            } else if (fileType == FLY_TYPE) {
                fileNames_fly.add(file.getOriginalFilename());
                readFlyFile(pathString);
                //System.out.println(list_fly);
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "{\"code\":0, \"msg\":\"success\", \"fileUrl\":\"" + pathString + "\"}";
    }

    //读取飞行参数数据
    public static void readFlyFile(String path) throws IOException, InvalidFormatException {
        File xlsFile = new File(path);

        // 工作表
        try (Workbook workbook = WorkbookFactory.create(xlsFile)) {

            // 表个数。
            int numberOfSheets = workbook.getNumberOfSheets();

            // 遍历表。
            for (int i = 0; i < numberOfSheets; i++) {
                Sheet sheet = workbook.getSheetAt(i);

                // 行数。
                int rowNumbers = sheet.getLastRowNum() + 1;

                // Excel第一行。
                Row temp = sheet.getRow(0);
                if (temp == null) {
                    continue;
                }
                //读取列数
                int cells = temp.getPhysicalNumberOfCells();
                //存储数据的数组
                String[] data_row = new String[cells];
                // 读数据。
                for (int row = 1; row < rowNumbers; row++) {
                    Row r = sheet.getRow(row);
                    for (int col = 0; col < cells; col++) {
                        data_row[col] = r.getCell(col).toString();
                    }
                    ;
                    list_fly.add(new FlyRow(data_row));
                }
            }
        }

    }


    //读取噪声数据
    public static void readNoiseFile(String path) throws IOException {
        File file = new File(path);
        FileReader fileReader = new FileReader(file);
        BufferedReader bufferedInputStream = new BufferedReader(fileReader);
        String line = bufferedInputStream.readLine();
        String[] headName = regex_noise(line);
        //读取每一行文件，保存到list对象
        while ((line = bufferedInputStream.readLine()) != null) {
            String[] data = regex_noise(line);
            NoiseRow noiseRow = new NoiseRow();
            noiseRow.setTime(Float.parseFloat(data[0]));
            //读取声道
            for (int i = 1; i < data.length; ++i) {
                noiseRow.getVocal_tract().add(Double.parseDouble(data[i]));
            }
            list_noise.add(noiseRow);
        }
    }

    //正则表达式
    public static String[] regex_noise(String line) {
        List<String> res = new ArrayList();
        Matcher m = Pattern.compile("\\S+").matcher(line);
        while (m.find()) {
            res.add(m.group());
        }
        String[] res_arr = (String[]) res.toArray(new String[res.size()]);
        return res_arr;
    }

    //获取到List中的数据进行分组，并转化为json对象
    public static String getOrginData(ArrayList<NoiseRow> list) {
        String res="{";
        //List转数组
        double time[] = new double[list.size()];
        //二维数组，二维时间，一维是声道
        double Vocal_tract[][] = new double[list.get(0).getVocal_tract().size()][list.size()];
        for (int i = 0; i < list.size(); i++) {
            NoiseRow row = list.get(i);
            time[i] = row.getTime();
            for (int j = 0; j < row.getVocal_tract().size(); j++) {
                Vocal_tract[j][i] = row.getVocal_tract().get(j);
            }
        }

        //数组转json
        JSONArray jsonArray = JSONArray.fromObject(time);
        String s = jsonArray.toString();
        res+="\"time\":"+s;
        for(int i=0;i<Vocal_tract.length;i++){
            JSONArray arr = JSONArray.fromObject(Vocal_tract[i]);
            String s_arr = arr.toString();
            res+=",\"Vocal_tract"+i+"\":"+s_arr;

        }
        res+=", \"msg\":\"success\"}";
        System.out.println(res);
        return res;
    }

    /*获取到3D声学球数据，并转化为json对象**/
    public static String get3DNoise(){
        String res="{";
        double res_arr[][]=new double[10][10];

        return res;
    }

    public static void main(String[] args) throws IOException {
        readNoiseFile("D:\\学习资料\\景德镇项目组\\软件开发输入\\噪声数据（非涉密非商密）.txt");
        getOrginData(list_noise);
    }
}
